package com.ruoyi.util;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownUtil {
    public static void download(String targetPath, String url) {
        try {
            download(targetPath, new URL(url));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public static void download(String targetPath, URL url) {

        String filePath = targetPath.replace("\\", "/");
        filePath = filePath.endsWith("/") ? filePath : (filePath + "/");
        String fileName = url.toString().substring(url.toString().lastIndexOf("/") + 1);
        String tmpName = fileName + "tmp";

        int bytesum = 0;
        int byteread = 0;

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(filePath + tmpName);

            byte[] buffer = new byte[1024];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                //System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
            fs.flush();
            fs.close();
            new File(filePath + tmpName).renameTo(new File(filePath + fileName));
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
            System.out.println(filePath + tmpName + " ===>>> " + e.getMessage());
            //e.printStackTrace();
        }
    }
}
